const mongoose = require('mongoose');
var News = require('../models/news.model');
var  Comment = require('../models/comment.model');
  exports.create = function(req, res, next) {
    const news = new News(req.body);
    news.save().then((data) => res.json(data));
  }

  exports.update = function(req,res,next){
    const id = req.params.id;

    News.findByIdAndUpdate(id,{$set: req.body},{new:false}).then(data=>{
      res.json(data);
    })
  }

  exports.remove = function(req,res,next){
    const id = req.params.id;
    News.findByIdAndDelete(id,(err,data)=>{
      res.json(data);
    })
  }

  //新增第二周模块、删除选中-------------------------------------
exports.removes = function(req,res,next){
  const ids = req.body.ids.split(',');
  //console.log(ids);
  if(ids.length>0){
    News.remove({_id: {$in: ids}}).then(data=>{
      res.json({"message":"数据已删除!"})
    })
  }
}

  exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var rows = req.body.rows ? req.body.rows : 10;



    var queryCondition = {};
    if(req.body.name && req.body.name.trim().length>0){
      queryCondition = {
          "title": new RegExp(req.body.name,'i')
        }
    }

    // console.log(req.body)
    if(req.body.cateId && req.body.cateId.trim().length>0){
      //console.log('haha');
      //console.log(req.body.cateId);
      queryCondition = {
        "cateId": req.body.cateId
      }
      if(req.body.name && req.body.name.trim().length>0){
        queryCondition = {
            "cateId": req.body.cateId,
            "title": new RegExp(req.body.name,'i')
          }
      }
    }

     //console.log(queryCondition)


    News.paginate(queryCondition, { page: +page, limit: +rows }, function(err, result) {
      //console.log(result);
      result.rows = result.docs;
      delete result.docs;
      async function getCount(result){
        for(let i=0;i<result.rows.length;i++){  // 这一行代码执行速度快不快？
          // 打印出10条新闻的ID
          // 我要等你先进行查询完毕
         await Comment.count({bdid :result.rows[i]._id },function(err,count){ // 这一行代码执行速度快不快？
            // 等你查询完毕以后，再进行赋值操作
            result.rows[i].number = count;  // 这一行代码执行速度快不快？
          })
        }
        //console.log(result);
        return result;
      }
      getCount(result).then(data=>{
        res.json(data);
      })
    });
  }

  exports.get = function(req,res,next){
    const id = req.params.id;
    News.findById(id).then(data=>{
      res.json(data);
    })
  }